// utils/request.js
import { API_URL } from '../config/config';
import { useUserStore } from '../store/user';

export default class Request {
  async http(param: any) {
    const { url, method, data = {}, header = {}, hideLoading = false, filter = false } = param;

    const userStore = useUserStore();
    // token
    const token = userStore.token;
    if (token) {
      header.Authorization = 'Bearer ' + token;
    }

    // show loading
    if (!hideLoading) {
      uni.showLoading({ title: '加载中...' });
    }

    return new Promise((resolve, reject) => {
      uni.request({
        url: API_URL + url,
        data,
        method,
        header,
        success: (res: any) => {
          if (!hideLoading) uni.hideLoading();

          const processed = this.transformResponse(res, filter);
          if (processed?.isError) {
            reject(processed.data);
          } else {
            resolve(processed.data);
          }
        },
        fail: (err) => {
          if (!hideLoading) uni.hideLoading();
          reject(err);
        },
      });
    });
  }

  private transformResponse(res, filter: boolean) {
    const { data } = res;
    if (!data) {
      return { isError: true, data: null };
    }

    const { code, message } = data;

    // 统一处理 401 未登录
    if (code === 401) {
      this.handle401();
      return { isError: true, data: null };
    } else {
      if (filter) {
        return { isError: false, data };
      } else {
        if (code === 200) {
          return { isError: false, data: data.data };
        } else {
          uni.showToast({
            title: message || '系统错误',
            icon: 'none',
          });
          return { isError: true, data: null };
        }
      }
    }
  }

  private handle401() {
    uni.showModal({
      title: '提示',
      content: '登录状态过期，是否重新登录？',
      success: (res) => {
        if (res.confirm) {
          const pages = getCurrentPages();
          const currentPage = pages[pages.length - 1] as any;
          const fullPath = currentPage?.$page?.fullPath || '';

          const userStore = useUserStore();
          userStore.loginRedirectUrl = fullPath;
          userStore.logout();

          uni.redirectTo({
            url: '/pagesB/login/index',
          });
        }
      },
    });
  }
}
